<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>根证书生成及签发证书Java实现 - macdfree&#39;s blog</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="macd" /><meta name="description" content="根证书生成及签发证书Java实现" />
<meta name="keywords" content="java, bouncycastle, 生成证书" />



<meta name="baidu-site-verification" content="Ak74Sk61bk" />
<meta name="google-site-verification" content="fAeFHpkrhfFS8LxdzXy0EtAPcVStv0faGn238sRF3L8" />


<meta name="generator" content="Hugo 0.54.0" />


<link rel="canonical" href="/posts/%E6%A0%B9%E8%AF%81%E4%B9%A6%E7%94%9F%E6%88%90%E5%8F%8A%E7%AD%BE%E5%8F%91%E8%AF%81%E4%B9%A6java%E5%AE%9E%E7%8E%B0/" />

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">




<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>


<link href="/dist/even.min.css?v=3.1.1" rel="stylesheet">
<link href="/lib/fancybox/jquery.fancybox-3.1.20.min.css" rel="stylesheet">




<meta property="og:title" content="根证书生成及签发证书Java实现" />
<meta property="og:description" content="根证书生成及签发证书Java实现" />
<meta property="og:type" content="article" />
<meta property="og:url" content="/posts/%E6%A0%B9%E8%AF%81%E4%B9%A6%E7%94%9F%E6%88%90%E5%8F%8A%E7%AD%BE%E5%8F%91%E8%AF%81%E4%B9%A6java%E5%AE%9E%E7%8E%B0/" />
<meta property="article:published_time" content="2018-05-17T14:02:39&#43;08:00"/>
<meta property="article:modified_time" content="2018-05-17T14:02:39&#43;08:00"/>

<meta itemprop="name" content="根证书生成及签发证书Java实现">
<meta itemprop="description" content="根证书生成及签发证书Java实现">


<meta itemprop="datePublished" content="2018-05-17T14:02:39&#43;08:00" />
<meta itemprop="dateModified" content="2018-05-17T14:02:39&#43;08:00" />
<meta itemprop="wordCount" content="992">



<meta itemprop="keywords" content="bouncycastle," />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="根证书生成及签发证书Java实现"/>
<meta name="twitter:description" content="根证书生成及签发证书Java实现"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">macdfree&#39;s blog</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">分类</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">标签</li>
      </a><a href="/archive/">
        <li class="mobile-menu-item">归档</li>
      </a>
  </ul>
</nav>
  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">macdfree&#39;s blog</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/archive/">归档</a>
      </li>
  </ul>
</nav>
    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">根证书生成及签发证书Java实现</h1>

      <div class="post-meta">
        <span class="post-time"> 2018-05-17 </span>
        <div class="post-category">
          
            <a href="/categories/java/"> java </a>
          
        </div>
        <span class="more-meta"> 约 992 字 </span>
        <span class="more-meta"> 预计阅读 2 分钟 </span>
        <span id="busuanzi_container_page_pv" class="more-meta"> <span id="busuanzi_value_page_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次阅读 </span>
      </div>
    </header>

    
    
<div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
<ul>
<li><a href="#背景">背景</a></li>
<li><a href="#实现">实现</a>
<ul>
<li><a href="#生成密钥对">生成密钥对</a></li>
<li><a href="#填充证书的基本信息和扩展信息">填充证书的基本信息和扩展信息</a></li>
<li><a href="#使用私钥进行对证书进行签名">使用私钥进行对证书进行签名</a></li>
<li><a href="#将私钥和签过名的证书存储到文件中">将私钥和签过名的证书存储到文件中</a></li>
</ul></li>
</ul>
</nav>
  </div>
</div>

    
    <div class="post-content">
      <p>Java中使用Keytool可以方便的实现证书的生成及存储。但实际项目中，可能需要在现有系统中实现证书的签发功能，这就要求通过Java代码实现证书的签发。</p>

<h1 id="背景">背景</h1>

<p>一个平台产品，为保证各项目与平台信息交互的安全性，计划通过非对称加密方式，私钥签名，公钥验签保证在传输过程中数据不被篡改。为实现此功能，平台中需要提供为各项目提供证书签发功能，各项目提交申请通过后平台会自动生成存储证书和私钥的pfx文件，各项目使用此pfx文件进行签名验签。</p>

<h1 id="实现">实现</h1>

<p>使用BouncyCastle开源加密库。生成证书大概包括以下步骤：</p>

<ol>
<li>生成密钥对</li>
<li>填充证书的基本信息和扩展信息</li>
<li>使用私钥进行对证书进行签名</li>
<li>将私钥和签过名的证书存储到文件中</li>
</ol>

<p>下面来看一下具体实现</p>

<h2 id="生成密钥对">生成密钥对</h2>

<p>此处使用RSA生成密钥对：</p>

<pre><code class="language-java">KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(&quot;RSA&quot;);
SecureRandom rand = SecureRandom.getInstance(&quot;SHA1PRNG&quot;);
keyPairGen.initialize(2048, rand);
return keyPairGen.generateKeyPair();
</code></pre>

<h2 id="填充证书的基本信息和扩展信息">填充证书的基本信息和扩展信息</h2>

<p>填充证书基本信息</p>

<pre><code class="language-java">X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
if (sEmailAddress != null) {
  nameBuilder.addRDN(BCStyle.E, sEmailAddress);
}
if (sCountryCode != null) {
  nameBuilder.addRDN(BCStyle.C, sCountryCode);
}
if (sState != null) {
  nameBuilder.addRDN(BCStyle.ST, sState);
}
if (sLocality != null) {
  nameBuilder.addRDN(BCStyle.L, sLocality);
}
if (sOrganisation != null) {
  nameBuilder.addRDN(BCStyle.O, sOrganisation);
}
if (sOrganisationUnit != null) {
  nameBuilder.addRDN(BCStyle.OU, sOrganisationUnit);
}
if (sCommonName != null) {
  nameBuilder.addRDN(BCStyle.CN, sCommonName);
}

BigInteger serial = new BigInteger(Long.toString(System.currentTimeMillis()));

X500Name subjectName = nameBuilder.build();

// 发行者名称
final X500Name issuerName;
if (rootCer == null) {
  // 如果没有根证书，则默认用当前证书
  issuerName = subjectName;
} else {
  issuerName = new X509CertificateHolder(rootCer.getEncoded()).getSubject();
}

Date notBefore = new Date(System.currentTimeMillis());
Date notAfter = new Date(notBefore.getTime() + ((long) iValidity * 24 * 60 * 60 * 1000));

JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, keyPair.getPublic());
</code></pre>

<p>需要注意的设置<code>RDN</code>的顺序需要倒序，因为通过查看源码发现在将<code>RDN</code>数组拼接成字符串时是倒序拼接的。<a href="https://github.com/dmlloyd/openjdk/blob/jdk9/jdk9/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java#L1055">源码查看</a></p>

<p>另一个需要注意的是<code>issuerName</code>必须和根证书中的<code>subName</code>保持一致，因为在存储证书链时，会检查前一个证书的<code>issuerName</code>是否等于后一个证书的<code>subName</code>。</p>

<p>填充扩展信息</p>

<pre><code class="language-java">// 添加扩展信息
final JcaX509ExtensionUtils u = new JcaX509ExtensionUtils();
if (rootCer != null) {
  // Authority key identifier 2.5.29.35
  certBuilder.addExtension(Extension.authorityKeyIdentifier, false, u.createAuthorityKeyIdentifier(rootCer));
}
// Subject key identifier 2.5.29.14
certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
    u.createSubjectKeyIdentifier(keyPair.getPublic()));
// Key usage 2.5.29.15
if (rootCer == null) {
  certBuilder.addExtension(Extension.keyUsage, true,
      new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
          | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign
          | KeyUsage.keyCertSign));
}
// Basic Constraints 2.5.29.19
certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(rootCer == null));
// Extended key usage 2.5.29.37
certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(
    new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
// CRL distribution points 2.5.29.31
String SERVER_BASE_REST_PKI_URL = &quot;123&quot;;
String CRL_URL = &quot;456&quot;;
DistributionPointName distributionPoint = new DistributionPointName(new GeneralNames(new GeneralName(
    GeneralName.uniformResourceIdentifier, SERVER_BASE_REST_PKI_URL + issuerName + CRL_URL)));
DistributionPoint[] distPoints = new DistributionPoint[1];
distPoints[0] = new DistributionPoint(distributionPoint, null, null);
certBuilder.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints));
</code></pre>

<p>以上扩展信息基本已包含了常用的信息。其中basicConstraints标识此证书是否是CA证书，即是否可以用此证书签发其他证书；keyUsage表示此证书的用途。</p>

<h2 id="使用私钥进行对证书进行签名">使用私钥进行对证书进行签名</h2>

<pre><code class="language-java">ContentSigner signer = new JcaContentSignerBuilder(signatureType.name()).build(rootKey);
X509CertificateHolder certHolder = certBuilder.build(signer);

return new JcaX509CertificateConverter().getCertificate(certHolder);
</code></pre>

<p>需要注意的是，如果是使用根证书签发证书，应该用根证书的私钥来进行签名。</p>

<h2 id="将私钥和签过名的证书存储到文件中">将私钥和签过名的证书存储到文件中</h2>

<pre><code class="language-java">KeyStore keyStore = null;
keyStore = KeyStore.getInstance(&quot;PKCS #12&quot;, &quot;BC&quot;);
keyStore.load(null, null);
keyStore.setKeyEntry(&quot;aaa&quot;, keyPair.getPrivate(), new char[] {}, new Certificate[] { certificate, rootCertificate });
FileOutputStream fos = new FileOutputStream(fKeyStoreFile)
keyStore.store(fos, cPassword);
fos.flush();
fos.close();
</code></pre>

<p>此处使用<code>PKCS #12</code>格式进行存储，包含私钥和证书链。</p>
    </div>

    
    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">macd</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">2018-05-17</span>
  </p>
  
  
</div>

    
    
<div class="post-reward">
  <input type="checkbox" name="reward" id="reward" hidden />
  <label class="reward-button" for="reward">赞赏支持</label>
  <div class="qr-code">
    
    
      <label class="qr-code-image" for="reward">
        <img class="image" src="/img/reward/wechat-qr-code.png">
        <span>微信打赏</span>
      </label>
    
      <label class="qr-code-image" for="reward">
        <img class="image" src="/img/reward/alipay-qr-code.png">
        <span>支付宝打赏</span>
      </label>
  </div>
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
          <a href="/tags/bouncycastle/">bouncycastle</a>
          
        </div>

      
      <nav class="post-nav">
        
          <a class="prev" href="/posts/vps%E5%88%9D%E5%A7%8B%E5%8C%96%E9%85%8D%E7%BD%AE%E8%AE%B0%E5%BD%95/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">VPS初始化配置记录</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        
          <a class="next" href="/posts/upsource%E4%BD%BF%E7%94%A8%E8%AE%B0%E5%BD%95/">
            <span class="next-text nav-default">Upsource使用记录</span>
            <span class="prev-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:macdfree@163.com" class="iconfont icon-email" title="email"></a>
      <a href="https://github.com/MACDfree" class="iconfont icon-github" title="github"></a>
  <a href="/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  <div class="busuanzi-footer">
    <span id="busuanzi_container_site_pv"> 本站总访问量 <span id="busuanzi_value_site_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次 </span>
    <span class="division">|</span>
    <span id="busuanzi_container_site_uv"> 本站总访客数 <span id="busuanzi_value_site_uv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 人 </span>
  </div>

  <span class="copyright-year">
    &copy; 
    
      2014 - 
    2019
    <span class="heart">
      <i class="iconfont icon-heart"></i>
    </span>
    <span class="author">macd</span>
    <span class="division">|</span>
    <span style="margin-left: 5px;">
      <img alt="buildstatus" src="https://travis-ci.org/MACDfree/hugoblog.svg?branch=master">
    </span>
  </span>
</div>
    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
<script src="/lib/highlight/highlight.pack.js?v=20171001"></script><script type="text/javascript" src="/lib/jquery/jquery-3.2.1.min.js"></script>
  <script type="text/javascript" src="/lib/slideout/slideout-1.0.1.min.js"></script>
  <script type="text/javascript" src="/lib/fancybox/jquery.fancybox-3.1.20.min.js"></script>
<script type="text/javascript" src="/dist/even.min.js?v=3.1.1"></script>








</body>
</html>
